package com.basic.business.order.service.impl;

import com.basic.business.order.domain.TOrdersStatus;
import com.basic.business.order.domain.TOrdersTimeLine;
import com.basic.business.order.mapper.ITOrdersStatusMapper;
import com.basic.business.order.mapper.ITOrdersTimeLineMapper;
import com.basic.business.order.service.ITOrdersStatusService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TOrdersStatusServiceImpl implements ITOrdersStatusService {

    @Resource
    private ITOrdersStatusMapper statusMapper;

    @Resource
    private ITOrdersTimeLineMapper timeLineMapper;

    @Transactional
    @Override
    public void insertPst(TOrdersStatus status) {
        statusMapper.insertPst(status);

        // 时间线入库
        TOrdersTimeLine timeLine = TOrdersTimeLine.createTOrdersTimeLine(status);
        timeLine.setOrderStatus(status.getOrderStatus());
        timeLineMapper.insert(timeLine);
    }

    @Override
    public void updateMainSid(long oldSid, long newSid, String newTid, String newShortId) {
        statusMapper.updateMainSid(oldSid, newSid, newTid, newShortId);
    }

    @Override
    public void updStatus(List<TOrdersStatus> statusList) {
        statusMapper.updStatus(statusList);

        Map<String, TOrdersStatus> statusMap = statusList.stream()
                .collect(Collectors.toMap(
                        TOrdersStatus::getShortId,
                        status -> status
                ));

        // 3. 获取补全信息
        List<TOrdersStatus> lists = statusMapper.getByShortId(statusList);

        List<TOrdersTimeLine> timeLineList = new ArrayList<>();
        lists.forEach(status -> {
            // 4. 从映射中获取对应的orderStatus并赋值
            TOrdersStatus sourceStatus = statusMap.get(status.getShortId());
            if (sourceStatus != null) {
                status.setOrderStatus(sourceStatus.getOrderStatus());
                status.setAccessTime(sourceStatus.getAccessTime()); // 同步accessTime
            }

            // 时间线入库
            TOrdersTimeLine timeLine = TOrdersTimeLine.createTOrdersTimeLine(status);
            timeLine.setOrderStatus(status.getOrderStatus());
            timeLineList.add(timeLine);
        });

        timeLineMapper.batchInsert(timeLineList);
    }

    @Override
    public void updatePst(TOrdersStatus status) {
        int cnt = statusMapper.updatePst(status);
        if (cnt > 0) {
            TOrdersTimeLine timeLine = TOrdersTimeLine.createTOrdersTimeLine(status);
            timeLine.setOrderStatus(status.getOrderStatus());
            timeLineMapper.insert(timeLine);
        }
    }

}
